import 'package:eshi/NumInput.dart';
import 'package:eshi/app/CommonFunctions.dart';
import 'package:eshi/app/MyApp.dart';
import 'package:eshi/app/settings/AboutPage.dart';
import 'package:eshi/app/settings/DataManage.dart';
import 'package:eshi/app/settings/DevicesManage.dart';
import 'package:eshi/app/shi/data/Config.dart';
import 'package:eshi/app/shi/data/System.dart';
import 'package:eshi/app/shi/widget/WebTextWidget.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

class SettingsPage extends StatefulWidget {
  final mail="liwanglai@gmail.com";
  final policyUrl="http://picmap.online/eshi/eshi_policy.html";

  const SettingsPage({super.key});

  @override
  State<StatefulWidget> createState() => SettingsState();
}
class SettingsState extends State<SettingsPage>{
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 等待Widget首次构建完成后再获取MediaQuery数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 此时context已准备就绪，可以安全获取MediaQuery
      setState(() {
        Config.isDarkMode = MediaQuery.of(context).platformBrightness == Brightness.dark;
      });
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: mText('配置页')),
      body: Padding(
        padding: EdgeInsets.all(16),
        child: ListView(
          children: items
        )
      )
    );
  }
  var language = Language.fromCode(Config.language);

  get items{
    return [
         // 设备管理
          _buildSectionTitle('设备管理'),
          _buildSettingItem(
            icon: Icons.person,
            title: Config.myName ?? mt('名称'),  //授权的第三方账号名称 授权第三方账号的话实现同账号设备共享   
            subtitle: Config.deviceName,
            onTap: () {
              prompt(Config.myName??"",(v){
                setState(() {
                  Config.myName =v;  
                });
              },title:mt("新名称"));
              ////弹窗修改名称
            },
            onLongClick:(){
              System.copy(System.deviceId);
              msg(mt("复制成功!"));
            }
          ),
          _buildSettingItem(
            icon: Icons.device_hub,
            title: '设备管理',
            subtitle: Config.bindDevices ?? '添加设备实现设备之间的资源共享(待实现)',
            onTap: () => _navigateToPage(context, '设备管理',body:DevicesManage()),
          ),
        
          _buildSettingItem(
            icon: Icons.security,
            title: '数据管理',
            subtitle: System.dataInfo,
            onTap: () => _navigateToPage(context, '数据管理',body:DataManage()),
          ),

          // _buildSectionTitle('网络管理'),
          // _buildSettingItem(   //开启或连接服务器 开的话显示连接到服务器的设备信息与设备管理 
          //   icon: Icons.notifications,
          //   title: '网络管理',
          //   subtitle: Config.netHost?? "暂未配置",
          //   onTap: () => {
          //     //显示可选服务器列表与自定义选项输入
          //   }
          // ),
          // _buildSettingItem(
          //   icon: Icons.font_download,
          //   title: '数据分享',
          //   subtitle: '自己构建的数据 可以设置收益值来赚钱赚钱之后改为赚了多少',
          //   onTap: () => _navigateToPage(context, ' '),
          // ),

          // _buildSettingItem(
          //   icon: Icons.font_download,
          //   title: '订阅管理',
          //   subtitle: '订阅的人创建更新后我会收到消息,',
          //   onTap: () => _navigateToPage(context, ''),
          // ),

          _buildSectionTitle('界面管理'),
          _buildSwitchItem(
            icon: Icons.dark_mode,
            title: '深色模式',
            subtitle: '夜间使用更舒适',
            value: Config.isDarkMode,
            onChanged: (isDark) {
              MyApp.of(context).themeMode = isDark ? ThemeMode.dark : ThemeMode.light;
              setState(() {
                Config.isDarkMode = isDark;
              });
            },
          ),
          _buildSettingItem(
            icon: Icons.language,
            title: '语言设置',
            subtitle: language.name,
            showTrailing: false,
            onTap: () => _showLanguageSelection(language,(lang){
                Config.language = lang.code;
                setState(() {
                  language = lang;
                });
                MyApp.of(context).locale =  lang.locale;
            }),
          ),
          // _buildSettingItem(
          //   icon: Icons.font_download,
          //   title: '字体大小',
          //   subtitle: '标准',
          //   onTap: () => _navigateToPage(context, '字体大小'),
          // ),
          // _buildSettingItem(
          //   icon: Icons.notifications,
          //   title: '背景色',
          //   subtitle: '未设置',
          //   onTap: () => _navigateToPage(context, '背景色'),
          // ),
          // 关于相关
          _buildSectionTitle('关于'),
          _buildSettingItem(
            icon: Icons.info,
            title: '关于我们',  //开启页面的同时顺带会检查版本更新
            subtitle: mt("版本号")+System.version,
            onTap: () => _navigateToPage(context, '关于我们',body: AboutPage()),
          ),
          _buildSettingItem(
            icon: Icons.policy,
            title: '隐私政策',
            subtitle: '用户数据收集与使用说明',
            onTap: () => _navigateToPage(context, '隐私政策',body:WebView("assets/doc/eshiPrivacyPolicy.html")),
            onLongClick: () => _launchUrl(widget.policyUrl),
          ),
          // _buildSettingItem(
          //   icon: Icons.help,
          //   title: '帮助中心',
          //   subtitle: '常见问题与反馈',
          //   onTap: () => _navigateToPage(context, '帮助中心'),
          // ),
          _buildSettingItem(
            icon: Icons.feedback,
            title: '意见反馈',
            subtitle: '告诉我们您的想法',
            onTap: () => _launchUrl("mailto:${widget.mail}"),
            onLongClick: () =>  _navigateToPage(context, 'Hello Word!',body:Center(child:  NumInputWidget())),
          ),

          // 退出登录
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 20),
            child: ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.redAccent,
                padding: EdgeInsets.symmetric(vertical: 14),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              child: mText(
                '退出',
                style: TextStyle(color: Colors.white, fontSize: 16),
              ),
              // onPressed: () => System.quit(),
              onPressed: () => _showLogoutDialog(context),
            ),
          )
          
    ];
  
  }


   // 构建分组标题
  Widget _buildSectionTitle(String title) {
    return Padding(
      padding: EdgeInsets.only(
        left: 16,
        top: 20,
        bottom: 8,
        right: 16,
      ),
      child: mText(
        title,
        style: TextStyle(
          color: Colors.grey[500],
          fontSize: 14,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }

  // 构建可点击的设置项
  Widget _buildSettingItem({
    required IconData icon,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
    VoidCallback? onLongClick,
    showTrailing=true,   //右侧更多图标 
    enabled = true,
  }) {
    return  ListTile(
      leading: Container(
        width: 40,
        height: 40,
        decoration: BoxDecoration(
          color: Colors.blueAccent.withOpacity(0.1),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Icon(icon, color: Colors.blueAccent, size: 20),
      ),
      title: mText(title),
      subtitle: mText(
        subtitle,
        style: TextStyle(fontSize: 12, color: Colors.grey[500]),
      ),
      trailing: (showTrailing) ?  Icon(Icons.arrow_forward_ios, size: 18, color: Colors.grey):null,
      onTap: onTap,
      contentPadding: EdgeInsets.symmetric(horizontal: 16),
      onLongPress: onLongClick,
      enabled:enabled
    );
  }

  // 构建带开关的设置项
  Widget _buildSwitchItem({
    required IconData icon,
    required String title,
    required String subtitle,
    required bool value,
    required ValueChanged<bool> onChanged,
  }) {
    return ListTile(
      leading: Container(
        width: 40,
        height: 40,
        decoration: BoxDecoration(
          color: Colors.greenAccent.withOpacity(0.1),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Icon(icon, color: Colors.greenAccent, size: 20),
      ),
      title: mText(title),
      subtitle: mText(
        subtitle,
        style: TextStyle(fontSize: 12, color: Colors.grey[500]),
      ),
      trailing: Switch(
        value: value,
        onChanged: onChanged,
        activeThumbColor: Colors.blueAccent,
      ),
      contentPadding: EdgeInsets.symmetric(horizontal: 16),
    );
  }

  // 跳转到详情页
  void _navigateToPage(BuildContext context, String title,{Widget? body}) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => Scaffold(
          appBar: AppBar(title: mText(title)),
          body: body ?? Center(child: mText('$title 详情页')),
        ),
      ),
    );
  }

  // 打开链接
  void _launchUrl(String url) async {
    if (await canLaunchUrl(Uri.parse(url))) {
      await launchUrl(Uri.parse(url));
    }
  }

  // 退出登录对话框
  void _showLogoutDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: mText('确认退出'),
        content: mText('确定退出应用嘛?'),
        actions: [
          TextButton(
            child: mText('取消'),
            onPressed: () => Navigator.pop(context),
          ),
          TextButton(
            style: TextButton.styleFrom(foregroundColor: Colors.redAccent),
            onPressed: () => System.quit(),
            child: mText('退出') // Navigator.pop(context),
          ),
        ],
      ),
    );
  }


// 显示语言选择对话框
  void _showLanguageSelection(Language selectedLanguage,void Function(Language lang) onChange) {
    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      clipBehavior: Clip.antiAlias,
      builder: (context) => Container(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 标题
            Padding(
              padding: EdgeInsets.only(bottom: 16),
              child: mText(
                '选择语言',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            
            // 语言选项列表
            Expanded(
              child: ListView.builder(
                shrinkWrap: true,
                itemCount: Language.values.length,
                itemBuilder: (context, index) {
                  final language = Language.values[index];
                  final isSelected = selectedLanguage.code == language.code;
                  
                  return ListTile(
                    // 国旗图标 + 语言名称
                    leading: mText(
                      language.icon,
                      style: const TextStyle(fontSize: 24),
                    ),
                    title: mText(language.name),
                    // 选中状态指示
                    trailing: isSelected
                        ? const Icon(Icons.check, color: Colors.blue)
                        : null,
                    // 点击选择语言
                    onTap: () {
                      onChange(language);
                      // _saveLanguageSelection(language);
                      Navigator.pop(context); // 关闭底部弹窗
                    },
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
// 用enum定义语言选项（包含扩展信息）
enum Language {
  // 定义支持的语言枚举值，附带代码、名称和图标
  chinese('zh_CN', '简体中文', '🇨🇳'),
   // 繁体中文（中国台湾）- 常用场景首选
  // chineseTraditionalTW('zh_TW', '繁體中文（台灣）', '🇨🇳'),
  // 可选：繁体中文（中国香港）- 若需区分香港地区
  chineseTraditionalHK('zh_HK', '繁體中文（香港）', '🇨🇳'),
  english('en_US', 'English', '🇺🇸'),
  // japanese('ja_JP', '日本語', '🇯🇵'),
  // korean('ko_KR', '한국어', '🇰🇷'),
  // french('fr_FR', 'Français', '🇫🇷');
  ;

  // 枚举成员的附加属性
  final String code; // 语言代码
  final String name; // 显示名称
  final String icon; // 图标（国旗emoji）

  // 构造函数
  const Language(this.code, this.name, this.icon);

  Locale get locale{
    final a = code.split("_");
    return Locale(a[0],a[1]);
  }
  // 从语言代码获取对应的枚举值（用于本地存储后反序列化）
  static Language fromCode(String code) {
    return Language.values.firstWhere(
      (lang) => lang.code == code,
      orElse: () => Language.chinese, // 默认返回中文
    );
  }

  static List<Locale> locales(){
    return Language.values.map((e) => e.locale ).toList();
  }
}

